package com.station.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.station.R;
import com.station.databinding.ActivityBaseBinding;
import com.station.listener.ViewClickListener;
import com.station.util.LoadLayoutModel;
import com.station.util.PreferencesUtil;

/**
 * Created by nbzl on 2017/8/9.
 */
public class BaseActivity extends AppCompatActivity {
    protected ActivityBaseBinding baseBinding;
    protected LocationManager locationManager;
    public Location location;
    protected LoadLayoutModel loadLayoutModel;
    protected ProgressDialog progressDialog;
    protected double Xlocation = 0,Ylocation = 0;
    public int REQUEST_CODE=1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        baseBinding= DataBindingUtil.setContentView(this, R.layout.activity_base);
        setSupportActionBar(baseBinding.toolbar);
        initLoadModel();
        after();
    }

    private void initLoadModel(){
        loadLayoutModel=new LoadLayoutModel(this,new LoadClick());
    }



    protected void after(){}

    protected void AddContentView(View view){
        baseBinding.content.removeAllViews();
        baseBinding.content.addView(view);
    }

    protected void handerBackToolar(String title){
        //getmNavButtonView();
        baseBinding.toolbar.setTitle(title);
        //baseBinding.toolbar.setTitleMargin(-20,0,0,0);
        //baseBinding.toolbar.setSubtitle(title);
        setSupportActionBar(baseBinding.toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Drawable drawable = baseBinding.toolbar.getNavigationIcon();//
        drawable.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(drawable);
        baseBinding.toolbar.setTitleTextColor(Color.WHITE);
        baseBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public void showProgress(String msg){
        if(progressDialog!=null){
            progressDialog=null;
        }
        progressDialog=new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }
    public void dissProgress(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    protected void showToast(String msg){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    public void reLoad(View v) {}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK){
            onResult(requestCode,data);
        }
    }

    public void onResult(int requestCode,Intent data){}


    class LoadClick implements ViewClickListener {

        @Override
        public void reRequest(View view) {
            reReques();
        }
    }
    public void reReques(){}

    //////////////////////////////////// GPS定位//////////////////////////////////////////
    protected void openGpsTip() {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_COARSE_LOCATION)){
                //已经禁止提示了
                Toast.makeText(BaseActivity.this, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
            }else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);

            }

        }else{
            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                // Toast.makeText(this, "GPS正常", Toast.LENGTH_SHORT).show();
            } else {
                showDialog();
            }
            // 打开gps模块
            String provider = LocationManager.GPS_PROVIDER;
            location = locationManager.getLastKnownLocation(provider);
            // 初始化当前坐标信息\
            if (location != null) {
                Ylocation = location.getLatitude();//维度（2位）
                Xlocation = location.getLongitude();//经度（3位）
                Log.e("Mytext",Xlocation+"--"+Ylocation);

                PreferencesUtil.getInstance(BaseActivity.this).setLatitude(Ylocation+"");
                PreferencesUtil.getInstance(BaseActivity.this).setLongitude(Xlocation+"");
                // Toast.makeText(MainTabActivity.this,
                // "Xlocation="+Xlocation+"---Ylocation="+Ylocation,
                // Toast.LENGTH_LONG).show();
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 200, locationListener);

        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length >0 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    //用户同意授权
                    //callPhone();
                }else{
                    //用户拒绝授权
                }
                break;
        }
    }

    private void showDialog() {
        // TODO Auto-generated method stub
        AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
        builder.setTitle("设置").setMessage("请开启Gps！");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                // startActivityForResult(intent,0); //此为设置完成后返回到获取界面
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseActivity.this.startActivity(intent);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private LocationListener locationListener = new LocationListener() {

        /**
         * GPS状态变化时触发
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
            Log.e("Mytext","onStatusChanged..." + provider);

        }

        /**
         * GPS开启时触发
         */
        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            Log.e("Mytext","onProviderEnabled..." + provider);

        }

        /**
         * GPS禁用时触发
         */
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            Log.e("Mytext","onProviderDisabled..." + provider);

        }

        /**
         * 位置信息变化时触发
         */
        @Override
        public void onLocationChanged(Location location) {
            Ylocation = location.getLatitude();
            Xlocation = location.getLongitude();//经度
            PreferencesUtil.getInstance(BaseActivity.this).setLatitude(Ylocation+"");
            PreferencesUtil.getInstance(BaseActivity.this).setLongitude(Xlocation+"");
            Log.e("Mytext","Xlocation-->"+Xlocation+"  Ylocation-->"+Ylocation);
        }

    };
}
